<?php
/*
 * Copyright (c) 2022.  Liuhongbin All rights reserved.
 * @domain http://dkyx.cc
 * @author liuhongbin <514660094@qq.com>
 */

namespace hiduoke\services\douyin;

use app\common\model\platform\Platform;
use app\common\model\platform\PlatformSetting;
use Overtrue\Socialite\Providers\DouYin;
use Overtrue\Socialite\SocialiteManager;
use think\Exception;
use think\facade\Cache;
use think\facade\Session;

class DouyinService
{
    protected $key = "";
    protected $secret = "";
    protected $redirect = "";
    protected $domain = "";
    protected $scopes = [];
    protected $plaid = 0;
    protected $addon = 0;
    protected $app;
    /**
     * @var DouYin
     */
    private $provider;
    /**
     * @var SocialiteManager
     */
    private SocialiteManager $socialite;
    /**
     * @var DouyinHttp
     */
    private DouyinHttp $http;

    public function __construct($plaid = 0, $addon = '')
    {
        $this->plaid = $plaid ?: get_plaid();
        $this->addon = $addon ?: get_addon();
        $this->init();
    }

    public function init()
    {
        $platform = (new Platform())->where(['plaid' => $this->plaid, 'type' => 4])->find();
        if (!$platform) throw new Exception('当前平台不存在', 10006);
        $config = $platform->config;
        $this->key = $config['client_key'] ?? '';
        $this->secret = $config['client_secret'] ?? '';
        $this->domain = $config['domain'] ?: request()->domain();
        $this->redirect = $this->getCallBackUrl();
        $this->scopes = $this->getScopes();
        $this->getProvider();
    }

    public function getScopes()
    {
        $scopes_setting = (new PlatformSetting())->getValueByKey("Scopes", $this->plaid);
        $scopes = [];
        foreach ($scopes_setting['scopes'] as $key => $value) {
            if (is_array($value)) {
                $scopes = array_merge($scopes, $value);
            } else if ($value) {
                $scopes[] = $value;
            }
        }
        $extra_scopes = explode(",", $scopes_setting['extra_scopes']);
        foreach ($extra_scopes as $key => $value) {
            if ($value) {
                $scopes[] = $value;
            }
        }
        return $scopes;
    }

    /**
     * @return \Overtrue\Socialite\Contracts\ProviderInterface
     */
    public function getProvider()
    {
        if ($this->provider) {
            return $this->provider;
        }
        $config = [
            'douyin' => [
                'client_id'     => $this->key,
                'client_secret' => $this->secret,
                'redirect'      => $this->redirect
            ]
        ];
        $this->socialite = new SocialiteManager($config);
        $this->provider = $this->socialite->create("douyin")->scopes($this->scopes);
        return $this->provider;
    }

    public function getCallBackUrl()
    {
        $vars = ['p' => get_plaid(), 'sid' => Session::getid(), 'back' => get_url()];
        $redirect = $this->domain . url('dy/oauth/callBack', $vars);
        return $redirect;
    }


    public function getUser($force_oauth = true)
    {
        $dy_user = Cache::get($this->getKey('dy_user'));
        if (!empty($dy_user)) {
            return $dy_user;
        } else {
            if ($force_oauth) {
                //记录当前地址
                Cache::set($this->getKey('target_url'), get_url());
                $url = $this->getProvider()->redirect();
                //跳转拉取授权
                to($url);
                return '';
            } else {
                return false;
            }
        }
    }

    /**
     * 获取抖音请求
     * @return DouyinHttp|false
     */
    public function getHttp($user = null)
    {
        $user = $user ?: $this->getUser(false);
        if ($user) {
            return $this->http ?? new DouyinHttp($user);
        } else {
            return false;
        }
    }

    /**
     * 获取缓存key
     * @param $string
     * @return string
     */
    protected function getKey($string)
    {
        return $string . Session::getid() . '_' . $this->plaid;
    }

}
